<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\severs\InReceiptSever;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class NicheClue
 * @package app\home\controller
 * 商机线索
 */
class NicheClue extends BaseController
{
    protected $title='商机线索';
    protected $table='niche_clue';

    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $where[] = ['nc.status', '>', -1];
            $haveAuth=false;
            if ($this->isHaveAuth('see_all')){
                $haveAuth=true;
            }
            elseif($this->isHaveAuth('see_depart')){
                $haveAuth=true;
                $where[]=['nc.departId','in',$this->dSons];
            }elseif($this->isHaveAuth('see_self')){
                $haveAuth=true;
                $where[]=['nc.createId','=',$this->uid];
            }
            if (!$haveAuth){
                return table_assign(1,'暂无查看权限');
            }
            if (isset($param['id'])&&$this->param['id']){
                $where[]=['nc.id','=',$param['id']];
            }
            if (isset($param['fromType'])&&$this->param['fromType']){
//                $where[]=['createId','=',$this->uid];
                $where[]=['nc.fromType','=',$param['fromType']];
            }

            if (isset($param['apply_time'])&&$this->param['apply_time']){
                $times=explode('~',$this->param['apply_time']);
                $where[]=['gTime','between',$times];
            }

            if (isset($param['fzName'])&&$this->param['fzName']){
                $where[]=['ad.name','like','%'.$param['fzName']."%"];
            }
            if (isset($param['createName'])&&$this->param['createName']){
                $where[]=['ad1.name','like','%'.$param['createName']."%"];
            }
            if (isset($param['text'])&&$this->param['text']){
                $where[]=['nc.punterName|nc.contactName|nc.content|nc.applane|nc.contactPhone|nc.contactJob','like','%'.$param['text']."%"];
            }
            $list = Db::name($this->table)
                ->alias('nc')
                ->leftJoin('admin ad', 'ad.id=nc.fzId')
                ->leftJoin('admin ad1', 'ad1.id=nc.createId')
                ->field('ad.name as fzName,ad1.name as createUser,nc.*')
                ->where($where)
                ->order('nc.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            $adminList=Db::name('admin')->where('status','1')
                ->field('id,name')
                ->select();
            view::assign('adminList',$adminList);
            return view();
        }
        
    }


    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param = $this->param;
            $mx=$param['mx']??[];

            if (!$mx){
             return to_assign(1,'请添加记录');
            }
            $mxIds=$mx['mxId']??[];
            $gtTime=$mx['gtTime']??[];
            $gtContent=$mx['gtContent']??[];
            Db::startTrans();
            try {
                $param['update_time'] = time();
                if ($param['id'] > 0) {
                    $rid=$this->param['id'];
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param, $this->title);
                } else {
                    $param['createId'] = $this->uid;
                    $param['departId'] = $this->did;
                    $param['create_time'] = time();
                    $rid = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $rid, $param, $this->title);
                }
                foreach ($gtTime as $key=>$v){
                    $mxData=[
                       'ncId' =>$rid,
                        'gtTime'=>$gtTime[$key]??'',
                        'gtContent'=>$gtContent[$key]??'',
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                    if (isset($mxIds[$key])&&$mxIds[$key]){
                        $mxData['id']=$mxIds[$key];
                        unset($mxData['create_time']);
                    }
                    Db::name('niche_clue_detail')->save($mxData);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败：'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $gtMxList=[];
            $detail=[];
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                $gtMxList=Db::name('niche_clue_detail')
                    ->where('ncId',$id)
                    ->where('status','>',-1)
                    ->field('id,gtTime,gtContent')->select()->toArray();
            };
            View::assign('detail', $detail);
            View::assign('gtMxList', $gtMxList);
            $adminList = Db::name('admin')->where('id', '>', 1)->where('status', 1)->field('id,name')->select();
            View::assign('adminList', $adminList);
            View::assign('id', $id);
            $thisDate=date('Y-m-d H:i:s');
            View::assign('thisDate',$thisDate);
            return view('form');
        }
    }

    public function info($id='')
    {
        $info=Db::name($this->table)->where('id',$id)->find();
        $gtMxList=Db::name('niche_clue_detail')
            ->where('ncId',$id)
            ->where('status','>',-1)
            ->field('id,gtTime,gtContent')->select()->toArray();
        $adminList = Db::name('admin')->where('id', '>', 1)->where('status', 1)->field('id,name')->select();
        View::assign('adminList', $adminList);
        View::assign(['detail'=>$info,'gtMxList'=>$gtMxList]);
        return view();
}
    public function delete()
    {

        $id = get_params("id");
        try {
            Db::name($this->table)->where('id', 'in', $id)->update(['status' => -1, 'deleted' => time()]);
            Db::name('niche_clue_detail')
                ->where('ncId',$id)
                ->where('status','>',-1)->update(['status' => -1, 'deleted' => time()]);
            add_log('delete', $id, request()->param(), $this->title);
        } catch (\Exception $e) {
            return to_assign(1, "删除失败" . $e->getMessage());
        }
        return to_assign(0, "删除成功");
    }

    public function removeMx()
    {
        $id=$this->param['id']??'';
        try {
            Db::name('niche_clue_detail')->where('id', '=', $id)->update(['status' => -1, 'deleted' => time()]);
            add_log('delete', $id, request()->param(), $this->title.'沟通明细');
        }catch (\Exception $e){
            return to_assign(1, "删除失败" . $e->getMessage());
        }
        return to_assign(0, "删除成功");
    }
    public function toPurveyor()
    {
        $id=$this->param['id']??'';
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $ids=explode(',',$id);
        $list=Db::name($this->table)->where('status','1')->where('id','in',$id)->select();
        if (count($list)!=count($ids)){
            return to_assign(1,'操作有误');
        }
        Db::startTrans();
        try {
            $data=[];
            foreach ($list as $v){
                $data[]=[
                    'createId'=>$this->uid,
                    'departId'=>$this->did,
                    'create_time'=>time(),
                    'update_time'=>time(),
                    'dw_type'=>2,
                    'saleIds'=>$v['fzId'],
                    'name'=>$v['punterName'],
                    'fdName'=>$v['contactName'],
                    'phoneNum'=>$v['contactPhone'],
                ];
            }
            Db::name('purveyor')->insertAll($data);
            Db::name($this->table)->where('status','1')->where('id','in',$id)
                ->update(['status'=>2,'doId'=>$this->uid,'update_time'=>time()]);
            add_log('toPur', $id, request()->param(), $this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }
    public function toOther()
    {
        $id=$this->param['id']??'';
        $usid=$this->param['uid']??'';
        if (!$id||!$usid){
            return to_assign(1,'参数缺失');
        }

        $ids=explode(',',$id);
        $list=Db::name($this->table)->where('status','1')->where('id','in',$id)->select();
        if (count($list)!=count($ids)){
            return to_assign(1,'操作有误');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('status','1')->where('id','in',$id)
                ->update(['status'=>1,'doId'=>$this->uid,'createId'=>$usid,'fromType'=>2,'update_time'=>time()]);
            add_log('toOther', $id, request()->param(), $this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {
                    $punterName=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    $contactName=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $contactPhone=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $contactJob=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $gTime=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                    $content=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $applane=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                    $fzId=(int)$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getFormattedValue();
                    if (!$punterName||!$contactName||!$contactPhone||!$contactJob
                        ||!$gTime||!$content||!$applane||!$fzId){
                        $warText="第".($j-1) ."行填写有误";
                            throw new Exception($warText);
                    }
                    $fzr=Db::name('admin')->where('id',$fzId)->value('id');
                    if (!$fzr){
                        $warText="第".($j-1) ."行负责人不存在";
                        throw new Exception($warText);
                    }
                    $importData[]=[
                        'punterName' => $punterName,
                        'contactName' => $contactName,
                        'contactPhone' => $contactPhone,
                        'contactJob' => $contactJob,
                        'gTime' => $gTime,
                        'content' => $content,
                        'applane' => $applane,
                        'fzId' => $fzId,
                        'createId' => $this->uid,
                        'departId' => $this->did,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];

                }

                if ($importData){
                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $importData,$this->title);
                }
                Db::commit();
            }

        }catch (Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }
}